package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.jgaeb.*;
import com.app.domain.yxtj.GroutingProcess;
import com.app.domain.yxtj.YxtjGrouting;
import com.app.domain.yxtj.YxtjResultJson;
import com.app.service.*;
import com.app.utils.HttpClients;
import com.app.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/jgaeb")
public class JgaebController {
    @Value("${yj.jgaeb.serverHost}")
    private String serverHost;
    @Value("${yj.jgaeb.processHost}")
    private String processHost;
    @Value("${yj.jgaeb.loginHost}")
    private String loginHost;
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadService uploadService;
    @Autowired
    JgaebService jgaebService;

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException {
        ExternalResponse externalResponse = null;
        LoginResult loginResult = null;
        List<LoginCookie> cookies = new ArrayList<>();
        try {
            Map<String, Object> map = HttpClients.doPost1(loginHost, new HashMap<>());
            String httpStr = String.valueOf(map.get("httpStr"));
            loginResult = (LoginResult) JSON.parseObject(StringUtil.replaceBlank(httpStr), LoginResult.class);
            cookies = (List<LoginCookie>) map.get("cookie");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (loginResult == null || loginResult.getFlag() != 1) {
            externalResponse = new ExternalResponse(0, "用户登录失败,请联系系统管理员", "");
            return externalResponse;
        } else {
          /*  cookies.put("userId", String.valueOf(loginResult.getData().getUserID()));
            cookies.put("userName", loginResult.getData().getName());
            cookies.put("departId", String.valueOf(loginResult.getData().getDepartId()));
            cookies.put("departName", loginResult.getData().getDepartName());
*/
        }
        int total = ids.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuffer responseContent = new StringBuffer();
        responseContent.append("本次共上传数据：【" + total + "】条,");


        List<YjData> yjDataList = yjDataService.findList(ids);
        List<List<YjData>> groupList = new ArrayList<>();
        yjDataList.stream().collect(Collectors.groupingBy(YjData::getBridge_code, Collectors.toList())).forEach((bridge_code, yjDataGroupList) -> {
            groupList.add(yjDataGroupList);
        });
        UploadParameter uploadParameter = uploadParameterService.findOne("18");
        for (List<YjData> yjData : groupList) {
            List<Integer> userIds = yjData.stream().map(o -> o.getId()).collect(Collectors.toList());
            Map<String, Object> map = yjDataService.findDate(userIds);
            PostGrouting postGrouting = jgaebService.getPostGrouting(yjData, uploadParameter, map);
            String s = JSON.toJSONString(postGrouting);
            PostGroutingResult groutingResult = jgaebService.sendMessage(serverHost, s, cookies);
            if (groutingResult.getSuccess() != null && groutingResult.getSuccess()) {
                for (YjData yjDatum : yjData) {
                    PostGroutings postGroutings = jgaebService.getPostGroutings(yjDatum, uploadParameter, map, groutingResult.getKid());
                    String s1 = JSON.toJSONString(postGroutings);
                    PostGroutingResult groutingsResult = jgaebService.sendMessage(processHost, s1, cookies);
                    if (groutingsResult.getSuccess() != null && groutingsResult.getSuccess()) {
                        updateState("1", String.valueOf(yjDatum.getId()));
                        succTotal++;
                    } else {
                        updateState("0", String.valueOf(yjDatum.getId()));
                        failTotal++;
                    }
                }
            } else {
                for (Integer userId : userIds) {
                    updateState("0", String.valueOf(userId));
                    failTotal++;
                }
            }
        }
        responseContent.append("成功【" + succTotal + "】条,失败" + failTotal + "条");
        externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        return externalResponse;
    }
    @RequestMapping("/add")
    @ResponseBody
    public String add(@RequestParam("deviceCode") String deviceCode,@RequestParam("ductCode")String ductCode, @RequestParam("bridgeCode") String bridgeCode, @RequestParam("mudjackDate") String mudjackDate,@RequestParam("beginTime")String beginTime,@RequestParam("endTime")String endTime) {

        return jgaebService.save(deviceCode,bridgeCode,ductCode,mudjackDate,beginTime,endTime);
    }
    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}
